package io.webfolder.cdp.channel;

import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.Endpoint;
import javax.websocket.EndpointConfig;
import javax.websocket.Session;

import io.webfolder.cdp.session.MessageHandler;
import io.webfolder.cdp.session.SessionFactory;

@ClientEndpoint
public class StandardWebSocketListener extends Endpoint implements javax.websocket.MessageHandler.Partial<String> {

	private final SessionFactory factory;

	private final MessageHandler handler;

	private final StringBuilder buffer = new StringBuilder(0);

	public StandardWebSocketListener(SessionFactory factory, MessageHandler handler) {
		this.factory = factory;
		this.handler = handler;
	}

	@Override
	public void onMessage(String data, boolean last) {
		if (last) {
			if (buffer.length() == 0) {
				handler.process(data.toString());
			} else {
				buffer.append(data);
				String message = buffer.toString();
				buffer.setLength(0);
				handler.process(message);
			}
		} else {
			buffer.append(data);
		}
	}

	@Override
	public void onClose(Session session, CloseReason closeReason) {
		factory.close();
		buffer.setLength(0);
	}

	@Override
	public void onOpen(Session session, EndpointConfig config) {
		// ignore
	}
}
